<!DOCTYPE html>
<html lang=zh-CN>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:description" content="samuel-24276的博客">
    <meta property="og:type" content="website">
    <meta name="description" content="samuel-24276的博客">
    <meta name="keyword"  content="aircloud">
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
        Qt的隐式共享与写时拷贝 - samuel-24276的博客 | samuel-24276&#39;s Blog
        
    </title>

    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/myblog/css/aircloud.css">

    
<link rel="stylesheet" href="/myblog/css/gitment.css">

    <!--<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">-->
    <link href="//at.alicdn.com/t/font_620856_28hi1hpxx24.css" rel="stylesheet" type="text/css">
    <!-- ga & ba script hoook -->
    <script></script>
<meta name="generator" content="Hexo 7.1.1"></head>

<body>

<div class="site-nav-toggle" id="site-nav-toggle">
    <button>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
    </button>
</div>

<div class="index-about">
    <i> Like what you do, do what you like </i>
</div>

<div class="index-container">
    
    <div class="index-left">
        
<div class="nav" id="nav">
    <div class="avatar-name">
        <div class="avatar ">
            <img src="/myblog/img/avatar.jpg" />
        </div>
        <div class="name">
            <i>samuel-24276</i>
        </div>
    </div>
    <div class="contents" id="nav-content">
        <ul>
            <li >
                <a href="/myblog/">
                    <i class="iconfont icon-shouye1"></i>
                    <span>主页</span>
                </a>
            </li>
            <li >
                <a href="/myblog/tags">
                    <i class="iconfont icon-biaoqian1"></i>
                    <span>标签</span>
                </a>
            </li>
            <li >
                <a href="/myblog/archives">
                    <i class="iconfont icon-guidang2"></i>
                    <span>存档</span>
                </a>
            </li>
            <li >
                <a href="/myblog/collect/">
                    <i class="iconfont icon-shoucang1"></i>
                    <span>收藏</span>
                </a>
            </li>
            <li >
                <a href="/myblog/about/">
                    <i class="iconfont icon-guanyu2"></i>
                    <span>关于</span>
                </a>
            </li>
            
            <li>
                <a id="search">
                    <i class="iconfont icon-sousuo1"></i>
                    <span>搜索</span>
                </a>
            </li>
            
        </ul>
    </div>
    
        <div id="toc" class="toc-article">
    
</div>
    
</div>


<div class="search-field" id="search-field">
    <div class="search-bg" id="search-bg"></div>
    <div class="search-container">
        <div class="search-input">
            <span id="esc-search"> <i class="icon-fanhui iconfont"></i></span>
            <input id="search-input"/>
            <span id="begin-search">搜索</span>
        </div>
        <div class="search-result-container" id="search-result-container">

        </div>
    </div>
</div>

        <div class="index-about-mobile">
            <i> Like what you do, do what you like </i>
        </div>
    </div>
    
    <div class="index-middle">
        <!-- Main Content -->
        


<div class="post-container">
    <div class="post-title">
        Qt的隐式共享与写时拷贝
    </div>

    <div class="post-meta">
        <span class="attr">发布于：<span>2022-10-04 17:25:21</span></span>
        
        <span class="attr">标签：/
        
        <a class="tag" href="/myblog/tags/#Qt" title="Qt">Qt</a>
        <span>/</span>
        
        
        </span>
        <span class="attr">访问：<span id="busuanzi_value_page_pv"></span>
</span>
</span>
    </div>
    <div class="post-content no-indent">
        <blockquote>
<p>文章来源：<a target="_blank" rel="noopener" href="https://0cch.com/2021/07/11/qt-implicit-sharing-copy-on-write/">Qt的隐式共享和写时拷贝 | 0CCh Blog</a></p>
</blockquote>
<p>不得不说Qt为了提高代码的运行效率做了很多伟大的工作，引入隐式共享和写时拷贝技术就是其中之一。该技术十分值得我们学习，一方面是因为它也可以运用到我们的代码中提高代码的运行效率，另一方面我们在理解其原理之后才能够更加高效的使用Qt。</p>
<p><strong>Qt中的隐式共享是指类中存在一个共享数据块指针，该数据块由数据和引用计数组成</strong>。</p>
<ul>
<li>当类型对象被创建时，共享数据块也被创建，并且设置引用计数为1。</li>
<li>当类型对象发生拷贝时，共享数据块共享其指针，并且递增引用计数（+1）。</li>
<li>当类型对象销毁时，共享数据块引用技术递减（-1），当引用计数归零时销毁数据块。</li>
<li>当类型对象调用方法有可能被修改时，采用写时拷贝机制，创建真正对象副本。</li>
</ul>
<p>使用隐式共享和写时拷贝的好处非常明显，在只读的情况下，拷贝对象的内存和CPU计算成本非常低。只有在真正修改对象的时候，才会发生对象拷贝。<strong>除了Qt中的普通类型以外，Qt的容器类型也大量采用了这种技术，这也是Qt容器和STL容器的一个显著的区别</strong>。</p>
<p>来看一个简单的例子：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// class QPenPrivate *d</span></span><br><span class="line"></span><br><span class="line">QPen::<span class="built_in">QPen</span>(<span class="type">const</span> QPen &amp;p) <span class="keyword">noexcept</span></span><br><span class="line">&#123;</span><br><span class="line">    d = p.d;</span><br><span class="line">    <span class="keyword">if</span> (d)</span><br><span class="line">        d-&gt;ref.<span class="built_in">ref</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">QPen::~<span class="built_in">QPen</span>()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">if</span> (d &amp;&amp; !d-&gt;ref.<span class="built_in">deref</span>())</span><br><span class="line">        <span class="keyword">delete</span> d;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">QPen::detach</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (d-&gt;ref.<span class="built_in">loadRelaxed</span>() == <span class="number">1</span>)</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">    QPenData *x = <span class="keyword">new</span> <span class="built_in">QPenData</span>(*<span class="built_in">static_cast</span>&lt;QPenData *&gt;(d));</span><br><span class="line">    <span class="keyword">if</span> (!d-&gt;ref.<span class="built_in">deref</span>())</span><br><span class="line">        <span class="keyword">delete</span> d;</span><br><span class="line">    x-&gt;ref.<span class="built_in">storeRelaxed</span>(<span class="number">1</span>); </span><br><span class="line">    d = x;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">QPen::setStyle</span><span class="params">(Qt::PenStyle s)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (d-&gt;style == s)</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    <span class="built_in">detach</span>();</span><br><span class="line">    d-&gt;style = s;</span><br><span class="line">    QPenData *dd = <span class="built_in">static_cast</span>&lt;QPenData *&gt;(d);</span><br><span class="line">    dd-&gt;dashPattern.<span class="built_in">clear</span>();</span><br><span class="line">    dd-&gt;dashOffset = <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到<code>Pen</code>的拷贝构造函数只是将共享数据块指针从<code>p</code>赋值到当前对象，然后增加其引用计数。当对象析构时，首先减少引用计数，然后判断引用计数是否归零，如果条件成立则释放对象。当调用<code>setStyle</code>函数修改对象的时候，函数调用了一个<code>detach</code>函数，这个<code>detach</code>函数检查当前的引用计数，若引用计数为1，证明没有共享数据块，可以直接修改数据。反之引用计数不为1，则证明存在共享改数据块的类，无法直接修改数据，需要拷贝一份新的数据。</p>
<p>现在看来，Qt似乎已经为我们考虑的十分周到了，不调用修改对象的函数是不会发生真正的拷贝的。那么需要我们做什么呢？答案是，Qt的使用者应该尽可能的避免误操作导致的数据拷贝。前面提到过，Qt认为可能发生写对象的操作都会真实的拷贝对象，其中要给典型的情况是：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">QVector&lt;<span class="type">int</span>&gt; test1&#123; <span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span> &#125;;</span><br><span class="line">QVector&lt;<span class="type">int</span>&gt; test2 = test1;</span><br><span class="line"><span class="type">int</span>* p = test2.<span class="built_in">data</span>();</span><br></pre></td></tr></table></figure>

<p><strong>这里看起来并没有发生对象的写操作，但是数据拷贝还是发生了，因为Qt认为这是一个可能发生写数据的操作，所以</strong><em><strong>在调用<code>data()</code>的时候就调用了<code>detach()</code>函数</strong></em>。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">inline</span> T *<span class="title">data</span><span class="params">()</span> </span>&#123; <span class="built_in">detach</span>(); <span class="keyword">return</span> d-&gt;<span class="built_in">begin</span>(); &#125;</span><br></pre></td></tr></table></figure>

<p>如果确定不会修改对象的数据应该明确告知编译器：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">QVector&lt;<span class="type">int</span>&gt; test1&#123; <span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span> &#125;;</span><br><span class="line"><span class="type">const</span> QVector&lt;<span class="type">int</span>&gt; test2 = test1;</span><br><span class="line">QVector&lt;<span class="type">int</span>&gt; test3 = test1;</span><br><span class="line"><span class="type">const</span> <span class="type">int</span>* p = test2.<span class="built_in">data</span>();</span><br><span class="line"><span class="type">const</span> <span class="type">int</span>* q = test3.<span class="built_in">constData</span>();</span><br></pre></td></tr></table></figure>

<p>其中</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">inline</span> <span class="type">const</span> T *<span class="title">data</span><span class="params">()</span> <span class="type">const</span> </span>&#123; <span class="keyword">return</span> d-&gt;<span class="built_in">begin</span>(); &#125;</span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="type">const</span> T *<span class="title">constData</span><span class="params">()</span> <span class="type">const</span> </span>&#123; <span class="keyword">return</span> d-&gt;<span class="built_in">begin</span>(); &#125;</span><br></pre></td></tr></table></figure>

<p>它们都不会调用<code>detach</code>函数拷贝对象。还是C++编程老生常谈那句话：<strong>在确定不修改对象的时候总是使用<code>const</code>来声明它，以便编译器对其做优化处理</strong>。</p>
<p>有时候我们并不是完全弄清楚编程环境中具体发生了什么，比如你可能不知道Qt的隐式共享和写时拷贝，但是保持良好的编程习惯，比如对于不修改的对象声明为<code>const</code>，有时候可以在不经意间优化了编写的代码，何乐而不为呢。</p>
<p>值得注意的是，我们应该尽量避免直接引用并通过引用修改Qt容器中的对象。千万不要这么做，因为可能会得到你不想看到的结果，例如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">QVector&lt;<span class="type">int</span>&gt; test1&#123; <span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span> &#125;;</span><br><span class="line">QVector&lt;<span class="type">int</span>&gt; test2 = test1;</span><br><span class="line"><span class="type">int</span>&amp; v = test1[<span class="number">1</span>];</span><br><span class="line">v = <span class="number">20</span>;</span><br></pre></td></tr></table></figure>

<p>这份代码不会出现问题，因为当表达式<code>test2 = test1</code>运行时，共享数据的引用计数递增为2，当调用<code>operator []</code>的时候由于<code>test1</code>不是<code>const</code>，所以会为<code>test1</code>拷贝一份副本。最后结果是：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">test1[<span class="number">1</span>] == <span class="number">20</span>;</span><br><span class="line">test2[<span class="number">1</span>] == <span class="number">2</span>;</span><br></pre></td></tr></table></figure>

<p>这样看来没有问题，但不幸的是我们有时候也会这样写：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">QVector&lt;<span class="type">int</span>&gt; test1&#123; <span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span> &#125;;</span><br><span class="line"><span class="type">int</span>&amp; v = test1[<span class="number">1</span>];</span><br><span class="line">QVector&lt;<span class="type">int</span>&gt; test2 = test1;</span><br><span class="line">v = <span class="number">20</span>;</span><br></pre></td></tr></table></figure>

<p>上面这份代码会带来一个意想不到的结果：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">test1[<span class="number">1</span>] == <span class="number">20</span>;</span><br><span class="line">test2[<span class="number">1</span>] == <span class="number">20</span>;</span><br></pre></td></tr></table></figure>

<p>因为在运行<code>int&amp; v = test1[1];</code>这句代码的时候，数据块的引用计数为1，<code>detach</code>函数认为数据块没有共享，所以无需拷贝数据。当执行<code>test2 = test1</code>的时候，Qt并不知道之前发生了什么，所以仅仅增加了引用计数，所以修改<code>v</code>同时修改了<code>test1</code>和<code>test2</code>。这不是我们想看到的结果，所以我们应该怎么做？注意代码执行的顺序么？得了吧，即使能保证自己会注意到代码的执行顺序问题，也不能保证其他人修改你的代码时会怎么做，**最好的做法是告诉大家，我们的项目有一条规则——禁止直接引用并通过引用修改Qt容器中的对象！**<em><strong>或者干脆，使用STL的容器吧</strong></em>。</p>
<p>最后，如果觉得Qt的隐式共享和写时拷贝技术很不错，碰巧你的项目的编写环境中也有Qt，那么使用<code>QSharedData</code>和<code>QSharedDataPointer</code>会让你的工作轻松很多。</p>
<hr>

        
            <div class="donate-container">
    <div class="donate-button">
        <button id="donate-button">赞赏</button>
    </div>
    <div class="donate-img-container hide" id="donate-img-container">
        <img id="donate-img" src="" data-src="/myblog/img/donate.jpg">
        <p> 感谢鼓励 </p>
    </div>
</div>
        
        <br />
        <div id="comment-container">
        </div>
        <div id="disqus_thread"></div>
        <div id="lv-container"></div>
        <div class="giscus"></div>
    </div>
</div>

    </div>
</div>


<footer class="footer">
    <ul class="list-inline text-center">
        
        

        

        

        
        <li>
            <a target="_blank"  href="https://github.com/samuel-24276">
                            <span class="fa-stack fa-lg">
                                <i class="iconfont icon-github"></i>
                            </span>
            </a>
        </li>
        

        

    </ul>
    
    <p>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://github.com/samuel-24276">samuel-24276&#39;s Page</a></span>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/">北京-未备案</a></span>
        <span>/</span>
        
        <span><a href="#">返回顶部</a></span>
        <span>/</span>
        
    </p>
    
    <p>
        <span id="busuanzi_container_site_pv">
            <span id="busuanzi_value_site_pv"></span>PV
        </span>
        <span id="busuanzi_container_site_uv">
            <span id="busuanzi_value_site_uv"></span>UV
        </span>
        Created By <a target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a>  Theme <a target="_blank" rel="noopener" href="https://github.com/aircloud/hexo-theme-aircloud">AirCloud</a></p>
</footer>




</body>

<script>
    // We expose some of the variables needed by the front end
    window.hexo_search_path = "search.json"
    window.hexo_root = "/myblog/"
    window.isPost = true
</script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<script src="/myblog/js/index.js"></script>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






    <script type="text/javascript">
       (function() {
           if (typeof LivereTower === 'function') { return; }

           var j, d = document.getElementById('lv-container');

           d.setAttribute('data-id','city');
           d.setAttribute('data-uid' , 'MTAyMC80OTA5OC8yNTU5Mw==');

           j = document.createElement('script');
           j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
           j.async = true;

           d.appendChild(j);
       })();
    </script>
    <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

</html>
